#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/inotify.h>
#include <stdio.h>

int read_process_inotify_fd(int fd)
{
    printf("process\n");
    int res;
    char event_buf[512];
    int event_size;
    int event_pos = 0;
    struct inotify_event *event;
    res = read(fd, event_buf, sizeof(event_buf));
    if(res < (int)sizeof(*event)) {
        if(errno == EINTR)
            return 0;
        printf("could not get event, %s\n", strerror(errno));
        return -1;
    }
    while(res >= (int)sizeof(*event)) {
        event = (struct inotify_event *)(event_buf + event_pos);
        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
        if(event->len) {

            if(event->mask & IN_CREATE) {
                printf("create file: %s\n", event->name);
            } else {
                printf("delete file: %s\n", event->name);
            }
        }
        event_size = sizeof(*event) + event->len;
        res -= event_size;
        event_pos += event_size;
        printf("loop\n");
    }
    return 0;

}

int main(int argc, char **argv)
{
    int ret;
    if (argc != 2) {
        printf("Usage: %s <dir>\n", argv[0]);
        return -1;
    }

    int mINotifyFd = inotify_init();
    int result = inotify_add_watch(mINotifyFd, argv[1], IN_DELETE | IN_CREATE);
    if (result < 0) {
        printf("inotify_add_watch error\n");
        return -1;
    }
    while (1) {
        ret = read_process_inotify_fd(mINotifyFd);
        if (ret) {
            printf("read_process_inotify_fd error\n");
            return -1;
        }
    }

    return 0;
}
